<template>
  <div class="workbench-container">
    <!-- 搜索筛选区域 -->
    <ContentWrap class="search-wrapper">
      <div class="search-header">
        <div class="header-icon">
          <Icon icon="ep:data-analysis" />
        </div>
        <div class="header-content">
          <h3 class="search-title">呼叫工作台</h3>
          <p class="search-subtitle">数据统计与分析</p>
        </div>
      </div>

      <div class="search-form-wrapper">
        <el-form
          :model="queryParams"
          :inline="true"
          label-width="60px"
          label-position="left"
          class="enhanced-search-form"
        >
          <div class="form-grid">
            <el-form-item label="部门" prop="agentNumber" class="form-item">
              <el-tree-select
                v-model="queryParams.deptId"
                :data="deptList"
                :props="defaultProps"
                check-strictly
                class="enhanced-select"
                node-key="id"
                placeholder="请选择归属部门"
                @change="queryParams.userId = undefined"
              >
                <template #prefix>
                  <Icon icon="ep:office-building" />
                </template>
              </el-tree-select>
            </el-form-item>

            <el-form-item label="员工" class="form-item">
              <el-select
                v-model="queryParams.userId"
                class="enhanced-select"
                clearable
                placeholder="请选择员工"
              >
                <template #prefix>
                  <Icon icon="ep:user" />
                </template>
                <el-option
                  v-for="(user, index) in userListByDeptId"
                  :key="index"
                  :label="user.nickname"
                  :value="user.id"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="时间" class="form-item time-picker-item">
              <el-dropdown
                trigger="click"
                placement="bottom-end"
                v-if="custom == false"
                class="time-dropdown"
              >
                <el-button class="time-btn">
                  <Icon icon="ep:calendar" class="btn-icon" />
                  <span class="btn-text">{{ datePickerTime }}</span>
                  <Icon icon="ep:arrow-down" class="arrow-icon" />
                </el-button>
                <template #dropdown>
                  <div v-show="custom == false" class="date-grid">
                    <el-button
                      v-for="button in dateBtn"
                      :key="button.dateType"
                      :type="button.type"
                      text
                      :disabled="button.disabled"
                      @click="pickDate(button.dateType)"
                      class="date-btn"
                    >
                      {{ button.dateType }}
                    </el-button>
                  </div>
                  <div v-show="custom == false" class="custom-btn" @click="handleCustom">
                    <Icon icon="ep:setting" class="custom-icon" />
                    自定义
                  </div>
                </template>
              </el-dropdown>

              <div v-if="custom" class="custom-picker">
                <el-date-picker
                  ref="datepicke"
                  v-model="valuepicker"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  type="datetimerange"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  @blur="pickChange"
                  @change="pickChange"
                  class="enhanced-date-picker"
                />
              </div>
            </el-form-item>
          </div>

          <div class="form-actions">
            <el-button @click="handleQuery" class="search-btn">
              <Icon icon="ep:search" class="btn-icon" />
              搜索
            </el-button>
            <el-button @click="resetQuery" class="reset-btn">
              <Icon icon="ep:refresh" class="btn-icon" />
              重置
            </el-button>
            <el-button type="primary" @click="preservaImg" class="export-btn">
              <Icon icon="ep:download" class="btn-icon" />
              保存为图片
            </el-button>
          </div>
        </el-form>
      </div>
    </ContentWrap>

    <!-- 主要内容区域 -->
    <div id="canvas-box" class="main-content">
      <div class="content-grid">
        <!-- 左侧主要区域 -->
        <div class="main-section">
          <!-- 统计卡片 -->
          <ContentWrap class="stats-wrapper">
            <div class="stats-header">
              <Icon icon="ep:data-line" class="stats-icon" />
              <h3 class="stats-title">数据概览</h3>
            </div>
            <div class="stats-grid">
              <div class="stat-card" v-for="item in titleMap" :key="item.id">
                <div class="stat-icon">
                  <el-image :src="item.imgUrl" class="icon-img" />
                </div>
                <div class="stat-content">
                  <div class="stat-label">{{ item.title }}</div>
                  <div class="stat-value">
                    {{ item.num }}
                    <span class="stat-unit">{{ item.unit }}</span>
                  </div>
                </div>
              </div>
            </div>
          </ContentWrap>

          <!-- 图表区域 -->
          <ContentWrap class="chart-wrapper">
            <div class="chart-header">
              <el-tabs v-model="activeTab" class="enhanced-tabs">
                <el-tab-pane name="outboundCallQuantity">
                  <template #label>
                    <div class="tab-label">
                      <Icon icon="ep:phone" class="tab-icon" />
                      <span>外呼数量统计</span>
                    </div>
                  </template>
                </el-tab-pane>
                <el-tab-pane name="phoneBill">
                  <template #label>
                    <div class="tab-label">
                      <Icon icon="ep:money" class="tab-icon" />
                      <span>话费账单统计</span>
                    </div>
                  </template>
                </el-tab-pane>
                <el-tab-pane name="callResult">
                  <template #label>
                    <div class="tab-label">
                      <Icon icon="ep:pie-chart" class="tab-icon" />
                      <span>呼叫结果统计</span>
                    </div>
                  </template>
                </el-tab-pane>
              </el-tabs>
            </div>

            <div class="chart-content">
              <div v-if="activeTab == 'outboundCallQuantity' && !isBar" class="chart-container">
                <Echart
                  :height="550"
                  :options="barChartOption"
                  v-loading="false"
                  class="enhanced-chart"
                />
              </div>
              <div v-if="activeTab == 'outboundCallQuantity' && isBar" class="empty-container">
                <el-empty
                  :image="emptyImg"
                  :image-size="200"
                  description="暂无数据"
                  class="enhanced-empty"
                />
              </div>

              <div v-if="activeTab == 'phoneBill' && !isPhone" class="chart-container">
                <Echart
                  :height="550"
                  :options="lineChartOption"
                  v-loading="false"
                  class="enhanced-chart"
                />
              </div>
              <div v-if="activeTab == 'phoneBill' && isPhone" class="empty-container">
                <el-empty
                  :image="emptyImg"
                  :image-size="200"
                  description="暂无数据"
                  class="enhanced-empty"
                />
              </div>

              <div v-if="activeTab == 'callResult'" class="chart-container">
                <Echart
                  :height="550"
                  :options="resChartOption"
                  v-loading="false"
                  class="enhanced-chart"
                />
              </div>
            </div>
          </ContentWrap>
        </div>

        <!-- 右侧侧边栏 -->
        <div class="sidebar-section">
          <!-- 时长统计饼图 -->
          <ContentWrap class="duration-wrapper">
            <div class="duration-header">
              <Icon icon="ep:timer" class="duration-icon" />
              <h3 class="duration-title">时长统计</h3>
            </div>
            <div class="duration-chart">
              <Echart
                :height="300"
                :options="topEchartsOption"
                v-loading="false"
                class="enhanced-chart"
              />
            </div>
          </ContentWrap>

          <!-- 通话记录表格 -->
          <ContentWrap class="records-wrapper">
            <div class="records-header">
              <Icon icon="ep:phone" class="records-icon" />
              <h3 class="records-title">最近通话</h3>
            </div>
            <div class="records-content">
              <el-table :data="list" class="enhanced-table">
                <el-table-column prop="prop" label="被叫号码" align="left" min-width="120">
                  <template #default="scope">
                    <div class="phone-cell">
                      <span :class="['status-dot', callType[scope.row.resultType]]"></span>
                      <el-button
                        type="primary"
                        link
                        @click="openDetail(scope.row.id)"
                        class="phone-link"
                      >
                        {{ scope.row.callee }}
                      </el-button>
                    </div>
                  </template>
                </el-table-column>

                <el-table-column
                  prop="callSecond"
                  label="通话时长"
                  align="left"
                  width="100"
                  show-overflow-tooltip
                >
                  <template #default="scope">
                    <div class="duration-cell">
                      <Icon icon="ep:timer" class="duration-icon" />
                      <span class="duration-text">
                        {{
                          scope.row.resultType == 99
                            ? '-'
                            : convertSecondsToMS(scope.row.callSecond)
                        }}
                      </span>
                    </div>
                  </template>
                </el-table-column>

                <el-table-column
                  prop="ownerUserName"
                  label="负责人"
                  align="left"
                  width="100"
                  show-overflow-tooltip
                >
                  <template #default="scope">
                    <div class="owner-cell">
                      <Icon icon="ep:user" class="owner-icon" />
                      <span class="owner-text">{{ scope.row.ownerUserName }}</span>
                    </div>
                  </template>
                </el-table-column>

                <el-table-column
                  prop="createTime"
                  label="时间"
                  align="left"
                  width="120"
                  show-overflow-tooltip
                  :formatter="dateFormatter"
                />
              </el-table>

              <div class="pagination-wrapper">
                <Pagination
                  :total="total"
                  :pager-count="5"
                  layout="total,prev, pager, next"
                  v-model:page="queryParams.pageNo"
                  v-model:limit="queryParams.pageSize"
                  @pagination="getList"
                />
              </div>
            </div>
          </ContentWrap>
        </div>
      </div>
    </div>

    <DetailDes ref="detailRef" />
  </div>
</template>

<script setup>
import DetailDes from '@/views/call/record/detail.vue'
import { dateFormatter } from '@/utils/formatTime'
import * as WorkBenchApi from '@/api/call/workbench'
import { defaultProps, handleTree } from '@/utils/tree'
import * as DeptApi from '@/api/system/dept'
import * as UserApi from '@/api/system/user'
import { userSelector } from '@/utils/deptUserSelect'
import { Calendar, Odometer, Finished, Position, Expand } from '@element-plus/icons-vue'
import { useUserStore } from '@/store/modules/user'
import getDateFn from '@/views/Home/getDateFn'
import dayjs from 'dayjs'
import { RecordApi } from '@/api/call/record'
import totalCountImg from '@/assets/img/totalCount.png'
import successCountImg from '@/assets/img/successCount.png'
import successRateImg from '@/assets/img/successRate.png'
import totalMinuteImg from '@/assets/img/totalMinute.png'
import avgMinuteImg from '@/assets/img/avgMinute.png'
import { convertSecondsToMS } from '@/utils/formatTime'
import html2canvas from 'html2canvas'
import emptyImg from '@/assets/img/empty.png'

const total = ref(0)
const list = ref([])
/*列表*/
const getList = async () => {
  const data = await RecordApi.getRecordPageBy(queryParams)
  list.value = data.list
  total.value = data.total
}

const callType = {
  1: 'success',
  99: 'error',
  90: 'error',
  91: 'error',
  92: 'error',
  93: 'error',
  94: 'error',
  95: 'error'
}
const titleMap = ref([
  {
    title: '外呼总数',
    name: 'totalCount',
    num: 0,
    id: 1,
    unit: '个',
    imgUrl: totalCountImg
  },
  {
    title: '接通总数',
    name: 'successCount',
    num: 0,
    id: 2,
    unit: '个',
    imgUrl: successCountImg
  },
  {
    title: '接通率',
    name: 'successRate',
    num: 0,
    id: 3,
    unit: '%',
    imgUrl: successRateImg
  },
  {
    title: '总通话时长',
    name: 'totalMinute',
    num: 0,
    id: 4,
    unit: '分钟',
    imgUrl: totalMinuteImg
  },
  {
    title: '平均通话时长',
    name: 'avgMinute',
    num: 0,
    id: 5,
    unit: '分钟',
    imgUrl: avgMinuteImg
  }
])
const userList = ref([])
const queryParams = reactive({
  deptId: useUserStore().getUser.deptId,
  userId: null,
  time: null,
  pageNo: 1,
  pageSize: 5
})
const activeTab = ref('outboundCallQuantity')

/** 打开详情*/
const detailRef = ref(null)
const openDetail = (id) => {
  detailRef.value.open(id)
}
/* 外呼数量统计 柱状图*/
const barChartOption = reactive({
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    },
    formatter: function (params) {
      // 自定义鼠标提示内容
      return `${params[0].name}<br/>成功: ${params[0].value}条<br/>失败: ${params[1].value}条<br/>总量: ${params[2].value}条`
    }
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  title: {
    text: '外呼数量统计',
    left: 'center'
  },
  xAxis: {
    data: [],
    name: '日期'
  },
  yAxis: {
    name: '数量'
  },
  series: [
    {
      type: 'bar', //成功
      data: [],
      barGap: '20%',
      barCategoryGap: '40%',
      barWidth: '20px',
      itemStyle: {
        color: '#67c23a'
      }
    },
    {
      type: 'bar', //失败
      data: [],
      barWidth: '20px',
      itemStyle: {
        color: '#f56c6c'
      }
    },
    {
      type: 'bar', //总量
      data: [],
      barWidth: '20px',
      itemStyle: {
        color: '#409fff'
      }
    }
  ]
})
const resChartOption = reactive({
  title: {
    text: '呼叫结果统计',
    left: 'center',
    top: '5%'
  },
  tooltip: {
    trigger: 'item'
  },
  legend: {
    orient: 'vertical',
    top: '10%',
    left: 'right'
  },
  series: [
    {
      // name: '呼叫结果',
      type: 'pie',
      radius: '50%',
      avoidLabelOverlap: false,
      itemStyle: {
        borderRadius: 10,
        borderColor: '#fff',
        borderWidth: 2
      },
      label: {
        show: true, // 显示标签
        formatter: '{b}: {c}' // 自定义标签格式
        // 你可以在这里自定义显示的内容
      },
      data: [],
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }
  ]
})
/*保存为图片*/
const preservaImg = () => {
  let el = document.getElementById('canvas-box')
  let options = {
    width: el.offsetWidth,
    height: el.offsetHeight,
    useCORS: true, // 是否尝试使用 CORS 从服务器加载图像
    allowTaint: false // 是否允许跨源图像污染画布
  }

  html2canvas(el, options).then((canvas) => {
    let imgData = canvas.toDataURL('image/jpeg') // 转base64
    fileDownload(imgData)
  })
}
/*下载图片方法*/
const fileDownload = (downloadUrl) => {
  let aLink = document.createElement('a')
  aLink.style.display = 'none'
  // 以防base64过长导致下载失败，所以将base64转成blob格式
  aLink.href = URL.createObjectURL(dataURIToBlob(downloadUrl))
  aLink.download = 'img.png'
  document.body.appendChild(aLink)
  aLink.click()
  document.body.removeChild(aLink)
}

// base64转blob方法
const dataURIToBlob = (dataURI) => {
  let binStr = atob(dataURI.split(',')[1]),
    len = binStr.length,
    arr = new Uint8Array(len)

  for (var i = 0; i < len; i++) {
    arr[i] = binStr.charCodeAt(i)
  }
  return new Blob([arr])
}
/* 话费账单统计 折线图 */
const lineChartOption = reactive({
  // tooltip: {
  //   trigger: 'item',
  //   formatter: function (params) {
  //     return `${params.name}:${params.value}` // 显示点的名称和数值
  //   },
  title: {
    text: '话费账单统计',
    left: 'center'
  },
  tooltip: {
    trigger: 'axis',
    formatter: function (params) {
      // 自定义鼠标提示内容
      return `${params[0].name}<br/> ${params[0].value}分钟`
    }
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },

  xAxis: {
    type: 'category',
    boundaryGap: false,
    name: '日期',
    data: []
  },
  yAxis: {
    type: 'value',
    name: '分钟'
  },
  series: [
    {
      data: [],
      type: 'line'
    }
  ]
})

/*时长统计饼状图*/
const topEchartsOption = reactive({
  title: {
    text: '时长统计',
    left: 'center'
  },
  tooltip: {
    trigger: 'item'
  },
  legend: {
    top: '10%',
    left: 'center'
  },
  series: [
    {
      name: '通话时长',
      type: 'pie',
      radius: ['40%', '70%'],
      center: ['50%', '60%'],
      data: [],
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }
  ]
})
/*获取时长统计*/
const getDurationStatistics = async () => {
  const data = await WorkBenchApi.getTimePieData(queryParams)
  const result = Object.entries(data).map(([name, value]) => ({ value, name }))
  topEchartsOption.series[0].data = result
}
const isPhone = ref(false)
/*获取按日期统计的员工消费账单（折线图）*/
const getBillLine = async () => {
  const data = await WorkBenchApi.getBillLineData(queryParams)
  isPhone.value = data.length == 0
  lineChartOption.xAxis.data = data.map((item) => item.time)
  lineChartOption.series[0].data = data.map((item) => item.value)
}

/*获取概要统计*/
const getSummary = async () => {
  const data = await WorkBenchApi.getWorkBench(queryParams)
  titleMap.value.forEach((item) => {
    if (data[item.name] !== undefined) {
      item.num = data[item.name].toFixed(2)
    }
  })
}
const isBar = ref(false)
/*获取外呼总量*/
const getBarData = async () => {
  const data = await WorkBenchApi.getTimeBar(queryParams)
  isBar.value = data.length == 0
  barChartOption.xAxis.data = data.map((item) => item.time)
  barChartOption.series[0].data = data.map((item) => item.successCount)
  barChartOption.series[1].data = data.map((item) => item.failCount)
  barChartOption.series[2].data = data.map((item) => item.totalCount)
}
// 获取结果统计
const getResult = async () => {
  const data = await WorkBenchApi.getUntResultType(queryParams)
  const options = Object.entries(data).map(([name, value]) => ({ value, name }))
  resChartOption.series[0].data = options
}
/** 搜索按钮操作 */
const handleQuery = () => {
  getDurationStatistics()
  getBillLine()
  getSummary()
  getBarData()
  getList()
  getResult()
}
/** 重置按钮操作 */
const resetQuery = async () => {
  queryParams.deptId = useUserStore().getUser.deptId
  queryParams.userId = null
  await pickDate('今天')
  handleQuery()
}
const deptList = ref([])
/** 根据选择的部门筛选员工清单 */
const userListByDeptId = computed(() => {
  return userSelector(userList.value, deptList.value, queryParams.deptId)
})
// 本季
const getNowSeaon = () => {
  const currentMonth = dayjs().month() // 当前月份
  let startOfQuarter, endOfQuarter
  // 根据当前月份确定季度的开始和结束时间
  if (currentMonth < 3) {
    // 第一季度
    startOfQuarter = dayjs().startOf('year')
    endOfQuarter = dayjs().month(2).endOf('month')
  } else if (currentMonth < 6) {
    // 第二季度
    startOfQuarter = dayjs().month(3).startOf('month')
    endOfQuarter = dayjs().month(5).endOf('month')
  } else if (currentMonth < 9) {
    // 第三季度
    startOfQuarter = dayjs().month(6).startOf('month')
    endOfQuarter = dayjs().month(8).endOf('month')
  } else {
    // 第四季度
    startOfQuarter = dayjs().month(9).startOf('month')
    endOfQuarter = dayjs().endOf('year')
  }
  return [startOfQuarter.format('YYYY-MM-DD HH:mm:ss'), endOfQuarter.format('YYYY-MM-DD HH:mm:ss')]
}
// 上季
const getLasSeaon = () => {
  const currentMonth = dayjs().month() // 当前月份
  let startOfLastQuarter, endOfLastQuarter

  // 根据当前月份确定上个季度的开始和结束时间
  if (currentMonth < 3) {
    // 如果当前是第一季度
    startOfLastQuarter = dayjs().subtract(1, 'year').month(9).startOf('month')
    endOfLastQuarter = dayjs().subtract(1, 'year').month(11).endOf('month')
  } else if (currentMonth < 6) {
    // 如果当前是第二季度
    startOfLastQuarter = dayjs().month(0).startOf('month')
    endOfLastQuarter = dayjs().month(2).endOf('month')
  } else if (currentMonth < 9) {
    // 如果当前是第三季度
    startOfLastQuarter = dayjs().month(3).startOf('month')
    endOfLastQuarter = dayjs().month(5).endOf('month')
  } else {
    // 如果当前是第四季度
    startOfLastQuarter = dayjs().month(6).startOf('month')
    endOfLastQuarter = dayjs().month(8).endOf('month')
  }
  return [
    startOfLastQuarter.format('YYYY-MM-DD HH:mm:ss'),
    endOfLastQuarter.format('YYYY-MM-DD HH:mm:ss')
  ]
}
// 日期默认值
const datePickerTime = ref('请选择日期')
const dateBtn = [
  { type: '', dateType: '天', disabled: true },
  { type: '', dateType: '今天', disabled: false },
  { type: '', dateType: '昨天', disabled: false },
  { type: '', dateType: '周', disabled: true },
  { type: '', dateType: '本周', disabled: false },
  { type: '', dateType: '上周', disabled: false },
  { type: '', dateType: '月', disabled: true },
  { type: '', dateType: '本月', disabled: false },
  { type: '', dateType: '上月', disabled: false },
  { type: '', dateType: '季', disabled: true },
  { type: '', dateType: '本季', disabled: false },
  { type: '', dateType: '上季', disabled: false }
]
// 日期快捷键选择
function pickDate(type) {
  if (type == '今天') {
    datePickerTime.value =
      getDateFn.getDate() + ' 00:00:00' + ' ~ ' + getDateFn.getDate() + ' 23:59:59'
  } else if (type == '昨天') {
    datePickerTime.value =
      getDateFn.getDate(-1) + ' 00:00:00' + ' ~ ' + getDateFn.getDate(-1) + ' 23:59:59'
  } else if (type == '本周') {
    datePickerTime.value =
      getDateFn.getMonday('s') + ' 00:00:00' + ' ~ ' + getDateFn.getMonday('e') + ' 23:59:59'
  } else if (type == '上周') {
    datePickerTime.value =
      getDateFn.getMonday('s', -1) +
      ' 00:00:00' +
      ' ~ ' +
      getDateFn.getMonday('e', -1) +
      ' 23:59:59'
  } else if (type == '本月') {
    datePickerTime.value =
      getDateFn.getMonth('s', 0) + ' 00:00:00' + ' ~ ' + getDateFn.getMonth('e', 0) + ' 23:59:59'
  } else if (type == '上月') {
    datePickerTime.value =
      getDateFn.getMonth('s', -1) + ' 00:00:00' + ' ~ ' + getDateFn.getMonth('e', -1) + ' 23:59:59'
  } else if (type == '本季') {
    datePickerTime.value = getNowSeaon().join('~')
  } else if (type == '上季') {
    datePickerTime.value = getLasSeaon().join('~')
  }
}
const custom = ref(false)
const valuepicker = ref('')
const pickChange = () => {
  if (valuepicker.value[0] != undefined && valuepicker.value[1] != undefined) {
    datePickerTime.value = valuepicker.value[0] + ' ~ ' + valuepicker.value[1]
  }
  custom.value = false
  valuepicker.value = ''
}
const datepicke = ref(null)
const handleCustom = async () => {
  custom.value = true
  await nextTick()
  datepicke.value.focus(true)
}
watch(
  () => datePickerTime.value,
  (val) => {
    queryParams.time = val.split('~').map((i) => i.trim())
  },
  { immediate: true, deep: true }
)
onMounted(async () => {
  deptList.value = handleTree(await DeptApi.getSimpleDeptList())
  userList.value = handleTree(await UserApi.getSimpleUserList())
  await pickDate('今天')
  await handleQuery()
})
</script>

<style lang="scss" scoped>
.workbench-container {
  padding: 16px;
  background: #f5f7fa;
  min-height: 100vh;

  @media (max-width: 768px) {
    padding: 8px;
  }
}

/* 搜索区域样式 */
.search-wrapper {
  margin-bottom: 16px;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 82, 204, 0.1);
}

.search-header {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 20px 24px;
  background: linear-gradient(135deg, #0052cc 0%, #1d4ed8 100%);
  color: white;
  border-radius: 10px;

  @media (max-width: 768px) {
    padding: 16px;
    flex-direction: column;
    text-align: center;
    gap: 12px;
  }
}

.header-icon {
  width: 48px;
  height: 48px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;

  @media (max-width: 768px) {
    width: 40px;
    height: 40px;
    font-size: 18px;
  }
}

.header-content {
  flex: 1;
}

.search-title {
  font-size: 20px;
  font-weight: 600;
  margin: 0 0 4px 0;

  @media (max-width: 768px) {
    font-size: 18px;
  }
}

.search-subtitle {
  font-size: 14px;
  opacity: 0.9;
  margin: 0;

  @media (max-width: 768px) {
    font-size: 12px;
  }
}

.search-form-wrapper {
  background: white;
  padding: 24px;

  @media (max-width: 768px) {
    padding: 16px;
  }
}

.enhanced-search-form {
  .form-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
    gap: 20px;
    margin-bottom: 24px;

    @media (max-width: 768px) {
      grid-template-columns: 1fr;
      gap: 16px;
      margin-bottom: 20px;
    }
  }

  .form-item {
    margin-bottom: 0;

    :deep(.el-form-item__label) {
      font-weight: 500;
      color: #374151;
    }
  }

  .time-picker-item {
    @media (max-width: 768px) {
      grid-column: 1 / -1;
    }
  }
}

.enhanced-select {
  width: 100%;

  :deep(.el-input__wrapper) {
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
    transition: all 0.2s ease;

    &:hover {
      box-shadow: 0 4px 12px rgba(0, 82, 204, 0.1);
    }

    &.is-focus {
      box-shadow: 0 4px 12px rgba(0, 82, 204, 0.2);
    }
  }
}

.time-dropdown {
  width: 100%;
}

.time-btn {
  width: 100%;
  justify-content: space-between;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  transition: all 0.2s ease;
  padding: 10px 12px;

  &:hover {
    box-shadow: 0 4px 12px rgba(0, 82, 204, 0.1);
  }

  .btn-icon {
    color: #6b7280;
  }

  .btn-text {
    flex: 1;
    text-align: left;
    margin: 0 8px;
    color: #374151;
  }

  .arrow-icon {
    color: #6b7280;
    font-size: 12px;
  }
}

.date-grid {
  display: grid;
  width: 260px;
  height: 222px;
  grid-template-columns: repeat(3, 1fr);
  grid-template-rows: repeat(4, 1fr);
  justify-items: center;
  grid-gap: 14px 0;
  padding: 20px 0;
}

.date-btn {
  width: 80%;
  padding: 8px 4px;
  margin: 0;
  font-size: 12px;
  border-radius: 6px;
  transition: all 0.2s ease;

  &:hover:not(:disabled) {
    background: rgba(0, 82, 204, 0.1);
    color: #0052cc;
  }

  &:disabled {
    font-weight: 600;
    color: #374151;
  }
}

.custom-btn {
  height: 40px;
  font-size: 14px;
  line-height: 38px;
  color: #0052cc;
  text-align: center;
  cursor: pointer;
  border-top: 1px solid #e5e7eb;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  transition: all 0.2s ease;

  &:hover {
    background: rgba(0, 82, 204, 0.05);
  }

  .custom-icon {
    font-size: 14px;
  }
}

.custom-picker {
  width: 100%;
}

.enhanced-date-picker {
  width: 100%;

  :deep(.el-input__wrapper) {
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
    transition: all 0.2s ease;

    &:hover {
      box-shadow: 0 4px 12px rgba(0, 82, 204, 0.1);
    }

    &.is-focus {
      box-shadow: 0 4px 12px rgba(0, 82, 204, 0.2);
    }
  }
}

.form-actions {
  display: flex;
  gap: 12px;
  justify-content: flex-end;

  @media (max-width: 768px) {
    flex-direction: column;
    gap: 8px;
  }
}

.search-btn {
  background: linear-gradient(135deg, #0052cc 0%, #1d4ed8 100%);
  border: none;
  border-radius: 8px;
  padding: 10px 20px;
  font-weight: 500;
  color: white;

  @media (max-width: 768px) {
    width: 100%;
  }

  .btn-icon {
    margin-right: 6px;
  }
}

.reset-btn {
  border: 2px solid #e5e7eb;
  color: #6b7280;
  border-radius: 8px;
  padding: 10px 20px;
  font-weight: 500;

  &:hover {
    border-color: #d1d5db;
    color: #374151;
  }

  @media (max-width: 768px) {
    width: 100%;
  }

  .btn-icon {
    margin-right: 6px;
  }
}

.export-btn {
  background: linear-gradient(135deg, #0052cc 0%, #1d4ed8 100%);
  border: none;
  border-radius: 8px;
  padding: 10px 20px;
  font-weight: 500;
  color: white;

  @media (max-width: 768px) {
    width: 100%;
  }

  .btn-icon {
    margin-right: 6px;
  }
}

/* 主要内容区域 */
.main-content {
  margin-top: 16px;
}

.content-grid {
  display: grid;
  grid-template-columns: 1fr 400px;
  gap: 16px;

  @media (max-width: 1200px) {
    grid-template-columns: 1fr;
    gap: 12px;
  }
}

.main-section {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.sidebar-section {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

/* 统计卡片区域 */
.stats-wrapper {
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 82, 204, 0.1);
  overflow: hidden;
}

.stats-header {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 20px 24px;
  background: #f8fafc;
  border-bottom: 1px solid rgba(0, 82, 204, 0.1);

  @media (max-width: 768px) {
    padding: 16px 20px;
  }
}

.stats-icon {
  color: #0052cc;
  font-size: 20px;
}

.stats-title {
  font-size: 16px;
  font-weight: 600;
  color: #374151;
  margin: 0;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 0;
  background: white;

  @media (max-width: 768px) {
    grid-template-columns: 1fr;
  }
}

.stat-card {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 24px;
  border-right: 1px solid #f1f5f9;
  transition: all 0.2s ease;

  &:last-child {
    border-right: none;
  }

  &:hover {
    background: rgba(0, 82, 204, 0.02);
  }

  @media (max-width: 768px) {
    padding: 20px;
    border-right: none;
    border-bottom: 1px solid #f1f5f9;

    &:last-child {
      border-bottom: none;
    }
  }
}

.stat-icon {
  flex-shrink: 0;
}

.icon-img {
  width: 48px;
  height: 48px;
  border-radius: 8px;

  @media (max-width: 768px) {
    width: 40px;
    height: 40px;
  }
}

.stat-content {
  flex: 1;
  min-width: 0;
}

.stat-label {
  font-size: 14px;
  color: #6b7280;
  margin-bottom: 4px;
  font-weight: 500;

  @media (max-width: 768px) {
    font-size: 12px;
  }
}

.stat-value {
  font-size: 24px;
  font-weight: 600;
  color: #1f2937;
  display: flex;
  align-items: baseline;
  gap: 8px;

  @media (max-width: 768px) {
    font-size: 20px;
  }
}

.stat-unit {
  font-size: 14px;
  color: #9ca3af;
  font-weight: 400;

  @media (max-width: 768px) {
    font-size: 12px;
  }
}

/* 图表区域 */
.chart-wrapper {
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 82, 204, 0.1);
  overflow: hidden;
  background: white;
}

.chart-header {
  background: #f8fafc;
  border-bottom: 1px solid rgba(0, 82, 204, 0.1);
}

.enhanced-tabs {
  :deep(.el-tabs__header) {
    margin: 0;
    padding: 0 24px;

    @media (max-width: 768px) {
      padding: 0 20px;
    }
  }

  :deep(.el-tabs__nav-wrap) {
    &::after {
      display: none;
    }
  }

  :deep(.el-tabs__item) {
    padding: 16px 20px;
    font-weight: 500;
    color: #6b7280;
    border-bottom: 2px solid transparent;
    transition: all 0.2s ease;

    &:hover {
      color: #0052cc;
    }

    &.is-active {
      color: #0052cc;
      border-bottom-color: #0052cc;
    }

    @media (max-width: 768px) {
      padding: 12px 16px;
      font-size: 14px;
    }
  }
}

.tab-label {
  display: flex;
  align-items: center;
  gap: 8px;
}

.tab-icon {
  font-size: 16px;

  @media (max-width: 768px) {
    font-size: 14px;
  }
}

.chart-content {
  padding: 24px;

  @media (max-width: 768px) {
    padding: 16px;
  }
}

.chart-container {
  border-radius: 8px;
  overflow: hidden;
}

.enhanced-chart {
  border-radius: 8px;
}

.empty-container {
  height: 500px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.enhanced-empty {
  :deep(.el-empty__description) {
    color: #6b7280;
    font-size: 14px;
  }
}

/* 时长统计区域 */
.duration-wrapper {
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 82, 204, 0.1);
  overflow: hidden;
  background: white;
}

.duration-header {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 20px 24px;
  background: #f8fafc;
  border-bottom: 1px solid rgba(0, 82, 204, 0.1);

  @media (max-width: 768px) {
    padding: 16px 20px;
  }
}

.duration-icon {
  color: #0052cc;
  font-size: 20px;
}

.duration-title {
  font-size: 16px;
  font-weight: 600;
  color: #374151;
  margin: 0;
}

.duration-chart {
  padding: 20px;

  @media (max-width: 768px) {
    padding: 16px;
  }
}

/* 通话记录区域 */
.records-wrapper {
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 82, 204, 0.1);
  overflow: hidden;
  background: white;
}

.records-header {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 20px 24px;
  background: #f8fafc;
  border-bottom: 1px solid rgba(0, 82, 204, 0.1);

  @media (max-width: 768px) {
    padding: 16px 20px;
  }
}

.records-icon {
  color: #0052cc;
  font-size: 20px;
}

.records-title {
  font-size: 16px;
  font-weight: 600;
  color: #374151;
  margin: 0;
}

.records-content {
  padding: 20px;

  @media (max-width: 768px) {
    padding: 16px;
    overflow-x: auto;
  }
}

.enhanced-table {
  :deep(.el-table__header) {
    background: #f8fafc;

    th {
      background: #f8fafc !important;
      color: #374151;
      font-weight: 600;
      border-bottom: 2px solid #e5e7eb;
      font-size: 12px;
      padding: 8px;
    }
  }

  :deep(.el-table__row) {
    &:hover {
      background: rgba(0, 82, 204, 0.02) !important;
    }
  }

  :deep(.el-table__cell) {
    padding: 8px;
    border-bottom: 1px solid #f1f5f9;
    font-size: 12px;
  }
}

.phone-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

.status-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  flex-shrink: 0;

  &.success {
    background-color: #67c23a;
  }

  &.error {
    background-color: #f56c6c;
  }
}

.phone-link {
  font-size: 12px;
  font-weight: 500;
  padding: 0;
}

.duration-cell,
.owner-cell {
  display: flex;
  align-items: center;
  gap: 6px;
}

.duration-icon,
.owner-icon {
  color: #6b7280;
  font-size: 12px;
  flex-shrink: 0;
}

.duration-text,
.owner-text {
  font-size: 12px;
  color: #374151;
  font-weight: 500;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;

  :deep(.el-pagination) {
    @media (max-width: 768px) {
      .el-pagination__sizes,
      .el-pagination__jump {
        display: none;
      }
    }
  }
}

/* 深色模式适配 */
@media (prefers-color-scheme: dark) {
  .workbench-container {
    background: #1f2937;
  }

  .search-wrapper,
  .stats-wrapper,
  .chart-wrapper,
  .duration-wrapper,
  .records-wrapper {
    background: #374151;
    border-color: rgba(255, 255, 255, 0.1);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
  }

  .search-form-wrapper,
  .stats-grid,
  .chart-content,
  .duration-chart,
  .records-content {
    background: #374151;
  }

  .stats-header,
  .chart-header,
  .duration-header,
  .records-header {
    background: #4b5563;
    border-color: rgba(255, 255, 255, 0.1);
  }

  .search-title,
  .stats-title,
  .duration-title,
  .records-title {
    color: #f9fafb;
  }

  .stat-label {
    color: #d1d5db;
  }

  .stat-value {
    color: #f9fafb;
  }

  .stat-unit {
    color: #9ca3af;
  }

  .stat-card {
    border-color: #4b5563;

    &:hover {
      background: rgba(96, 165, 250, 0.1);
    }
  }

  .enhanced-tabs {
    :deep(.el-tabs__header) {
      background: #4b5563;
    }

    :deep(.el-tabs__item) {
      color: #d1d5db;

      &:hover,
      &.is-active {
        color: #60a5fa;
      }

      &.is-active {
        border-bottom-color: #60a5fa;
      }
    }
  }

  .enhanced-table {
    :deep(.el-table__header) {
      background: #4b5563;

      th {
        background: #4b5563 !important;
        color: #f9fafb;
        border-bottom-color: #6b7280;
      }
    }

    :deep(.el-table__cell) {
      border-bottom-color: #4b5563;
    }
  }

  .duration-text,
  .owner-text {
    color: #f9fafb;
  }

  .duration-icon,
  .owner-icon {
    color: #d1d5db;
  }

  .btn-text {
    color: #f9fafb;
  }

  .enhanced-select,
  .enhanced-date-picker {
    :deep(.el-input__wrapper) {
      background: #4b5563;
      border-color: #6b7280;

      .el-input__inner {
        color: #f9fafb;
      }
    }
  }

  .time-btn {
    background: #4b5563;
    border-color: #6b7280;

    &:hover {
      border-color: #60a5fa;
    }

    .btn-text {
      color: #f9fafb;
    }
  }

  .date-btn {
    &:hover:not(:disabled) {
      background: rgba(96, 165, 250, 0.1);
      color: #60a5fa;
    }

    &:disabled {
      color: #f9fafb;
    }
  }

  .custom-btn {
    color: #60a5fa;
    border-top-color: #4b5563;

    &:hover {
      background: rgba(96, 165, 250, 0.1);
    }
  }
}
</style>
